package com.mindskip.xzs.service.impl;

import cn.hutool.core.io.FileUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.mindskip.xzs.configuration.property.QnConfig;
import com.mindskip.xzs.configuration.property.SystemConfig;
import com.mindskip.xzs.service.FileUpload;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;

@Service
public class FileUploadImpl implements FileUpload {
    private final Logger logger = LoggerFactory.getLogger(FileUpload.class);
    private final SystemConfig systemConfig;


    @Autowired
    public FileUploadImpl(SystemConfig systemConfig) {
        this.systemConfig = systemConfig;
    }

    /**
     * oss上传文件
     */
    @Override
    public String uploadFile(InputStream inputStream, long size, String extName) {

        QnConfig qnConfig = systemConfig.getQn();

        String endpoint = qnConfig.getUrl();
        String accessKeyId = qnConfig.getAccessKey();
        String accessKeySecret = qnConfig.getSecretKey();
        String bucketName = qnConfig.getBucket();

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            String objectName = System.currentTimeMillis()+"."+ FileUtil.getSuffix(extName);

            ossClient.putObject(bucketName, objectName, inputStream);

            return String.format("https://%s.%s/%s", bucketName, endpoint, objectName);

        } catch (Exception oe) {
            oe.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }


//        QnConfig qnConfig = systemConfig.getQn();
//        Configuration cfg = new Configuration(Region.region2());
//        UploadManager uploadManager = new UploadManager(cfg);
//        Auth auth = Auth.create(qnConfig.getAccessKey(), qnConfig.getSecretKey());
//        String upToken = auth.uploadToken(qnConfig.getBucket());
//        try {
//            Response response = uploadManager.put(inputStream, null, upToken, null, null);
//            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
//            return qnConfig.getUrl() + "/" + putRet.key;
//        } catch (QiniuException ex) {
//            logger.error(ex.getMessage(), ex);
//        }
//        return null;
//    }
}
